<template>
  <div>
    <el-dialog
      :model-value="visible"
      :title="data.id != '' ? '编辑用户角色' : '添加用户角色'"
      width="850"
      :close-on-click-modal="false"
      @close="cls"
    >
      <el-form
        ref="formDept"
        :model="emp"
        label-width="150px"
        :rules="rules"
        style="width: 800px"
      >
        <el-form-item label="角色：">
          <el-input
            v-model="data.identification"
            placeholder="请输入账号"
            @blur="chick"
          />
        </el-form-item>
        <el-form-item label="角色名称：">
          <el-input
            v-model="data.name"
            placeholder="请输入账号"
            @blur="chick"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="cls">关闭</el-button>
          <el-button type="primary" @click="save"> 保存 </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>
<script setup>
import { reactive, ref } from "vue";
import { ElMessage } from "element-plus";
import { saveRole, updateRole } from "@/api/system/role.js";

const data = ref({
  id: "",
  identification: "",
  name: ""
});

//定义角色列表
const roles = ref([{ id: 2, name: "管理员" }]);
//定义组件属性
const props = defineProps({
  visible: {
    type: Boolean,
    default: true
  }
});

//同名引用
const formDept = ref(null);
const rules = reactive({
  identification: [
    { required: true, message: "请输入角色身份", trigger: "blur" }
  ],
  name: [{ required: true, message: "请输入角色名称", trigger: "blur" }]
});

//定义事件
const emits = defineEmits(["close", "reflush"]);
function cls() {
  emits("close");
  emits("reflush");
}

//初始化方法，用于传参
function init(params) {
  if (params != undefined) data.value = params;
}

//暴露init方法，方便父组件调用
defineExpose({ init });

//保存
async function save() {
  const valid = formDept.value.validate;
  if (!valid) return;
  let res = ref({});
  if (emp.value.id == 0) {
    //发送数据
    console.log(emp.value);
    res.value = await saveEmp(data.value);
  } else {
    res.value = await updateEmp(data.value);
  }
  if (res.value.code == 200) {
    ElMessage({
      message: "保存成功",
      type: "success"
    });
    emp.value = {};
    cls();
  }
}
</script>
<style scoped></style>
